#-*- coding: utf-8 -*-
import csv
from util.Location import Location
from util.Metadata import Metadata
from StringIO import StringIO

parameters = ["ID", "CATEGORY", "NAME", "ADDRESS", "LAT", "LONG", "TEL", "NOTE", "SUBCATEGORY", "OPENING", "CLOSING", "CREATOR", "CREATED", "VERSION", "SOURCE", "VALID"]

def str_cmp_nocase(str1, str2):
    return str1.lower() == str2.lower()

def parse_csv(str_csv):
    f = StringIO(str_csv)
    spamreader = csv.reader(f, delimiter=',', quotechar='"')
    
    #dizionario che associa ad ogni campo la sua posizione nel CSV
    fields = {}
    
    #lista che contiene gli header
    header = spamreader.next()
    
    for i in range(len(header)):
        f = header[i]
        if str_cmp_nocase(f, 'id'):
            fields['id'] = i
        elif str_cmp_nocase(f, 'category'):
            fields['category'] = i
        elif str_cmp_nocase(f, 'subcategory'):
            fields['subcategory'] = i
        elif str_cmp_nocase(f, 'name'):
            fields['name'] = i
        elif str_cmp_nocase(f, 'address'):
            fields['address'] = i
        elif str_cmp_nocase(f, 'lat'):
            fields['lat'] = i
        elif str_cmp_nocase(f, 'long'):
            fields['long'] = i
        elif str_cmp_nocase(f, 'opening'):
            fields['opening'] = i
        elif str_cmp_nocase(f, 'closing'):
            fields['closing'] = i
        elif str_cmp_nocase(f, 'creator'):
            fields['creator'] = i
        elif str_cmp_nocase(f, 'created'):
            fields['created'] = i
        elif str_cmp_nocase(f, 'valid'):
            fields['valid'] = i
        elif str_cmp_nocase(f, 'version'):
            fields['version'] = i
        elif str_cmp_nocase(f, 'source'):
            fields['source'] = i
        elif str_cmp_nocase(f, 'tel'):
            fields['tel'] = i
        elif str_cmp_nocase(f, 'note'):
            fields['note'] = i
        
    locations_dict = {}
    metadata = None
    
    for row in spamreader:
        location = Location()
        location.id = row[fields['id']]
        location.category = row[fields['category']]
        location.name = row[fields['name']]
        location.address = row[fields['address']]
        location.lat = float(row[fields['lat']])
        location.long = float(row[fields['long']])
        location.opening = row[fields['opening']]
        location.closing = row[fields['closing']]
        if fields.get('subcategory') != None:
            location.subcategory = row[fields['subcategory']]
        if fields.get('tel') != None:
            location.tel = row[fields['tel']]
        if fields.get('note') != None:
            location.note = row[fields['note']]
        
        #metadata lo istanzio solo una volta
        if metadata is None:
            metadata = Metadata()
            metadata.creator = row[fields['creator']]
            metadata.created = row[fields['created']]
            metadata.source = row[fields['source']]
            metadata.version = row[fields['version']]
            metadata.valid = row[fields['valid']]
        
        #pero li assegno ad ogni istanza di location  
        location.metadata = metadata
        locations_dict[location.id] = location
    
    return locations_dict

'''
Dato un Dizionario di Location crea il relativo csv

@param locations_dict: Dizionario che associa Oggetti di tipo Location ai relativi id
@return: Stringa che contiene il risultato in csv
@author: Simone Rondelli
'''
def write_csv(locations_dict):
    csv = u'"ID","CATEGORY","NAME","ADDRESS","LAT","LONG","TEL","NOTE","SUBCATEGORY","OPENING","CLOSING","CREATOR","CREATED","VERSION","SOURCE","VALID"\n'
    
    for k in locations_dict.keys():
        loc = locations_dict[k]
        #raddoppio i doppi apici (" -> "") altrimenti nella riconversione troviamo errori
        csv += '"' + k + '",'
        csv += '"' + loc.category.replace('"', '""') + '",'
        csv += '"' + loc.name.replace('"', '""') + '",'
        csv += '"' + loc.address.replace('"', '""') + '",'
        csv += '"' + str(loc.lat) + '",'
        csv += '"' + str(loc.long) + '",'
        csv += '"' + loc.tel + '",'
        csv += '"' + loc.note.replace('"', '""') + '",'
        csv += '"' + loc.subcategory.replace('"', '""') + '",'
        csv += '"' + loc.opening + '",'
        csv += '"' + loc.closing + '",'
        csv += '"' + loc.metadata.creator + '",'
        csv += '"' + loc.metadata.created + '",'
        csv += '"' + loc.metadata.version + '",'
        csv += '"' + loc.metadata.source + '",'
        csv += '"' + loc.metadata.valid + '"'
        csv += '\n'
        
    if type(csv) == str:
        csv = unicode(csv,'utf8')
    
    return csv
